package com.example.test_activity.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.test_activity.R;
import com.example.test_activity.MVP.view.AddCourseActivity;
import com.example.test_activity.dao.DBSyllabus;
import com.example.test_activity.entity.SerializableObject;
import com.example.test_activity.http.HttpUtil;
import com.example.test_activity.utils.GetTime;
import com.example.test_activity.utils.NoDoubleClickListener;
import com.example.test_activity.utils.WeekUtil;
import com.example.test_activity.viewUtil.CoordinatorMenu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

import static android.app.Activity.RESULT_OK;

/**
 * Created by 旭 on 2017/3/29/029.
 */

public class SyllabusFragment extends Fragment {

    private View view;
    private Spinner spinner;

    private GridView gridView;
    //GridView绑定的集合
    private List<Map<String, String>> list = new ArrayList<>();
    //临时存储数据的集合
    private List<Map<String, String>> temp = new ArrayList<Map<String, String>>();
    private SimpleAdapter adapter;

    //存入本地
    private List<Map<String, String>> dece_loc = new ArrayList<>();

    private ImageView refresh;
    private ImageView head;
    private CoordinatorMenu menu;
    private TextView tv_week;

    private GetTime time = new GetTime();
    WeekUtil weekUtil = new WeekUtil();

    private int index = time.getTime();
    private int week;
    private String mId;

    private int now_index;

    private SerializableObject serializableMap = new SerializableObject();

    public SyllabusFragment(String id)
    {
        this.mId = id;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_syllabus, container, false);
        init();
        onClickSpinner();

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();

        head.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (menu.isOpened()) {
                    menu.closeMenu();
                } else {
                    menu.openMenu();
                }
            }
        });

        refresh.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                dialog_fresh();
            }
        });

        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                String syllName = list.get(position).get("syllabus");

                if (syllName.equals(" "))
                {
                    dialog_add(position/7,position%7+1);
                }else {
                    dialog_delete(syllName,position/7,(position%7+1));
                }

                return false;
            }
        });
    }

    private void init() {
        week = time.getWeek();
        getColor(week);

        refresh = (ImageView) view.findViewById(R.id.fg_refresh);
        head = (ImageView) view.findViewById(R.id.fg_head);
        spinner = (Spinner) view.findViewById(R.id.spinner_syllabus);
        menu = (CoordinatorMenu) getActivity().findViewById(R.id.menu);

        gridView = (GridView) view.findViewById(R.id.grid_view);
        adapter = new SimpleAdapter(getContext(),list,R.layout.syllabus_item,
                new String[]{"syllabus"},
                new int[]{R.id.text_test});
        gridView.setAdapter(adapter);
    }

    //获得周几的颜色
    private void getColor(int week) {
        //红色
        String color = "#FF0000";
        int[] res = new int[]{R.id._7, R.id._1, R.id._2, R.id._3, R.id._4, R.id._5, R.id._6};
        tv_week = (TextView) view.findViewById(res[week]);
        tv_week.setTextColor(Color.parseColor(color));
    }


    //下拉栏
    private void onClickSpinner() {
        String[] mItem = getResources().getStringArray(R.array.week);
        mItem[index] = mItem[index] + "(本周)";
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), R.layout.spinner_item, mItem);
        adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setSelection(index);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                now_index = position;
                if (DBSyllabus.instance(getContext(), mId).tableIsExist()) {
                    refreshData(now_index);
                } else {
                    getData();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //得到数据库中需求数据
    private void get(int week) {
        init_list();
        //遍历数据库中的信息
        for (Map<String, String> map : DBSyllabus.instance(getContext(), mId).getAllSyllabus()) {
            //筛选有课的信息
            if (!map.get("num").equals(" ")) {
                Map<String, String> list_map = temp.get(Integer.valueOf(map.get("num"))*7+(Integer.valueOf(map.get("weekend"))-1));
                if (Integer.valueOf(map.get("min")) > week || Integer.valueOf(map.get("max")) < week
                        || ((week % 2) != Integer.valueOf(map.get("flag"))) && Integer.valueOf(map.get("flag")) != 2) {
                } else {
                    list_map.put("syllabus",map.get("name"));
                }
            }
        }
        list.clear();
        list.addAll(temp);
    }

    //初始化list
    private void init_list() {
        temp.clear();
        for (int i = 0; i < 35; ++i) {
            Map<String, String> map = new HashMap<>();

            map.put("syllabus"," ");
            temp.add(map);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case RESULT_OK:
                serializableMap = (SerializableObject) data.getExtras().get("map");
                Map<String, String> map = serializableMap.getMap();
                List<Map<String, String>> list_temp = new ArrayList<>();
                list_temp.add(map);
                DBSyllabus.instance(getContext(), mId).saveSyllabus(list_temp);

                refreshData(now_index);
                break;
        }
    }

    private void dialog_fresh()
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("重新获取课表?");
        builder.setCancelable(true);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                getData();
                spinner.setSelection(index);
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private void dialog_add(final int num, final int weekend)
    {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        dialog.setTitle("确认添加课程?");
        dialog.setCancelable(true);
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(getActivity(), AddCourseActivity.class);
                intent.putExtra("num",String.valueOf(num));
                intent.putExtra("weekend",String.valueOf(weekend));
                startActivityForResult(intent, 0);
                dialog.dismiss();
            }
        });
        dialog.create().show();
    }

    private void dialog_delete(final String syllName, final int num, final int weekend)
    {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setCancelable(true);
        builder.setTitle("确认删除课程"+syllName+"?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Map<String,String> map = new HashMap<String, String>();
                map.put("name",syllName);
                map.put("num",String.valueOf(num));
                map.put("weekend",String.valueOf(weekend));

                DBSyllabus.instance(getContext(),mId).deleteData(map);
                refreshData(now_index);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    //获取数据
    private void getData()
    {
        HttpUtil.getInstance().sendGetPost().getSyllabus()
                .map(new Function<ResponseBody, ResponseBody>() {
                    @Override
                    public ResponseBody apply(@NonNull ResponseBody responseBody) throws Exception {
                        dece_loc.clear();
                        dece_loc.addAll(weekUtil.Data(responseBody.string()));

                        DBSyllabus.instance(getContext(), mId).saveSyllabus(dece_loc);

                        return responseBody;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull ResponseBody responseBody) {

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        refreshData(index);
                    }
                });
    }

    private void refreshData(final int week)
    {
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(@NonNull ObservableEmitter<Object> e) throws Exception {
                get(week);
                e.onNext(" ");
                e.onComplete();
            }
        })
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Object o) {

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        adapter.notifyDataSetChanged();
                    }
                });

    }
}
